import {
  getInfo,
  getMenus,
  loginByUsername,
  logout,
  judgeUserRole,
  updateLastedLoginTime
} from '@/api/login'
import {
  Message
} from 'element-ui'
import {
  getToken,
  removeToken,
  setLoginName,
  setLoginPwd,
  setToken
} from '@/utils/auth'

import {
  dictSelectAll
} from '@/api/e-formula/dict/index';
// 保存数据字典
function getAllDataDic() {
  let allDic
  try {
    allDic = localStorage.getItem('DATA-DIC')
  } catch (e) {
    allDic = {}
  }
  return allDic || {}
}
// 保存数据字典
function getAllDataMapDic() {
  let allMapDic
  try {
    allMapDic = localStorage.getItem('DATA-MAP-DIC')
  } catch (e) {
    allMapDic = {}
  }
  return allMapDic || {}
}

const user = {
  state: {
    allDic: getAllDataDic(),
    allMapDic: getAllDataMapDic(),
    user: '',
    info: {},
    status: '',
    code: '',
    token: getToken(),
    name: '',
    tenantId: '',
    avatar: '',
    introduction: '',
    roles: [],
    commonMenu: {},
    menus: undefined,
    eleemnts: undefined,
    permissionMenus: undefined,
    setting: {
      articlePlatform: []
    }
  },

  mutations: {

    SET_DIC: (state, allDic) => {
      state.allDic = allDic
    },
    SET_MAP_DIC: (state, allMapDic) => {
      state.allMapDic = allMapDic
    },
    SET_CODE: (state, code) => {
      state.code = code
    },
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_INTRODUCTION: (state, introduction) => {
      state.introduction = introduction
    },
    SET_SETTING: (state, setting) => {
      state.setting = setting
    },
    SET_STATUS: (state, status) => {
      state.status = status
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_USER: (state, info) => {
      state.info = info
    },
    SET_TENANT_ID: (state, tenantId) => {
      state.tenantId = tenantId
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_MENUS: (state, menus) => {
      state.menus = menus
    },
    SET_ELEMENTS: (state, elements) => {
      state.elements = elements
    },
    SET_COMMONMENU: (state, commonMenu) => {
      state.commonMenu = commonMenu
    },
    LOGIN_SUCCESS: () => {
      console.log('login success')
    },
    LOGOUT_USER: state => {
      state.user = ''
    },
    SET_PERMISSION_MENUS: (state, permissionMenus) => {
      state.permissionMenus = permissionMenus
    }
  },

  actions: {
    // 用户名登录
    LoginByUsername({
      commit
    }, userInfo) {
      const username = userInfo.username.trim()
      return new Promise((resolve, reject) => {
        loginByUsername(username, userInfo.password).then(response => {
          const data = response
          if (data.access_token === '' || data.access_token === undefined) {
            Message({
              message: '账户或密码错误！',
              type: 'warning'
            })
            return Promise.reject('error')
          } else {
            const token = 'Bearer ' + data.access_token;
            setToken(token)

            setLoginName(username)
            setLoginPwd(userInfo.password)

            commit('SET_TOKEN', token);

            // setRefreshToken(data.refresh_token)
            // commit('SET_REFRESH_TOKEN', data.refresh_token)
            resolve()
            // 向user表中更新 最后登录 时间
            updateLastedLoginTime().then(res)
          }
        }).catch(error => {
          console.log(JSON.stringify(error))
          reject(error)
        })
      })
    },
    // 获取字典包
    GetAllDictionaryKeyValue({
      commit
    }, code) {
      const data = code || 'tc'
      return new Promise((resolve, reject) => {
        dictSelectAll(data)
          .then(response => {
            if (response.status === 200) {
              commit('SET_DIC', response.data.groupList)
              commit('SET_MAP_DIC', response.data.groupMap)
              localStorage.setItem('DATA-DIC', JSON.stringify(response.data.groupList))
              localStorage.setItem('DATA-MAP-DIC', JSON.stringify(response.data.groupMap))
              // console.log(JSON.stringify(response.data.groupMap), '数据字典为搜索')
            } else {
              console.log('数据字典为null')
            }
            resolve()
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    // 获取用户信息
    GetInfo({
      commit
    }) {
      return new Promise((resolve, reject) => {
        getInfo().then(response => {
          const data = response
          Config.id = '12'
          Config.I18n = response.dictData

          commit('SET_ROLES', 'admin')
          commit('SET_NAME', data.name)
          commit('SET_USER', data)
          commit('SET_TENANT_ID', data.tenantId)
          commit('SET_AVATAR', 'http://git.oschina.net/uploads/42/547642_geek_qi.png?1499487420')
          commit('SET_INTRODUCTION', data.description)
          const menus = {}
          for (let i = 0; i < data.menus.length; i++) {
            menus[data.menus[i].code] = true
          }
          commit('SET_MENUS', menus)
          const elements = {}
          for (let i = 0; i < data.elements.length; i++) {
            elements[data.elements[i].code] = true
          }
          commit('SET_ELEMENTS', elements)

          // 常用菜单
          const commonMenu = {}
          commonMenu.firstCommonMenu = data.commonMenu[0]
          commonMenu.secondCommonMenu = data.commonMenu[1]
          commonMenu.thirdCommonMenu = data.commonMenu[2]
          commit('SET_COMMONMENU', commonMenu)

          judgeUserRole().then(res => {
            const type = res.data
            if (type === '1') { // 当前用户没有任何角色
              Message({
                message: '请联系管理员添加角色',
                type: 'warning'
              })
              reject()
            } else if (type === '2') { // 当前用户有且只有默认角色
              console.log('type 为2')
              Message({
                message: '请联系管理员添加角色',
                type: 'warning'
              })
              resolve(response)
            } else { // 当前用户有其他角色
              resolve(response)
            }
          })

          // // 判断角色为空
          // if (type === '1') {
          //   Message({
          //     message: '请联系管理员添加角色',
          //     type: 'warning'
          //   })
          //   // 赋予默认角色
          //   reject()
          // } else {
          //   resolve(response)
          // }
        }).catch(error => {
          reject(error)
        })

        // 获得显示的菜单
        getMenus().then(response => {
          commit('SET_PERMISSION_MENUS', response)
        })
      })
    },

    // 第三方验证登录
    // LoginByThirdparty({ commit, state }, code) {
    //   return new Promise((resolve, reject) => {
    //     commit('SET_CODE', code)
    //     loginByThirdparty(state.status, state.email, state.code).then(response => {
    //       commit('SET_TOKEN', response.data.token)
    //       setToken(response.data.token)
    //       resolve()
    //     }).catch(error => {
    //       reject(error)
    //     })
    //   })
    // },

    // 登出
    LogOut({
      commit,
      state
    }) {
      return new Promise((resolve, reject) => {
        const token = state.token
        commit('SET_TOKEN', '')
        logout(token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_MENUS', undefined)
          commit('SET_ELEMENTS', undefined)
          commit('SET_PERMISSION_MENUS', undefined)
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({
      commit
    }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        commit('SET_MENUS', undefined)
        commit('SET_ELEMENTS', undefined)
        commit('SET_PERMISSION_MENUS', undefined)
        removeToken()
        resolve()
      })
    }
  }
}

export default user
